package cn.iocoder.yudao.module.infra.tts.impl.dashscope;

import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.module.infra.tts.TTSConfig;
import cn.iocoder.yudao.module.infra.tts.impl.SimpleTTSApi;
import com.alibaba.dashscope.audio.ttsv2.SpeechSynthesisParam;
import com.alibaba.dashscope.audio.ttsv2.SpeechSynthesizer;
import com.alibaba.dashscope.audio.ttsv2.enrollment.Voice;
import com.alibaba.dashscope.audio.ttsv2.enrollment.VoiceEnrollmentService;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.nio.ByteBuffer;

import static java.awt.SystemColor.text;

// https://bailian.console.aliyun.com/?tab=model#/api-key
// https://help.aliyun.com/zh/model-studio/cosyvoice-java-api?spm=a2c4g.11186623.help-menu-2400256.d_2_4_0_0.24db3560zNdt3f
@Slf4j
@Service("tts-dashscope")
public class DashScopeTTSApi extends SimpleTTSApi {
    private static String targetModel = "cosyvoice-v2";
    private static String prefix = "lm";
    private TTSConfig.Config aliConfig;

    @Resource
    private TTSConfig ttsConfig;

    @PostConstruct
    public void init() {
        aliConfig = ttsConfig.getService("dashscope");
    }

    @Override
    public String createCloneVoice(String fileUrl) {
        final VoiceEnrollmentService service = new VoiceEnrollmentService(aliConfig.getApiKey());
        try {
            final Voice myVoice = service.createVoice(targetModel, prefix, fileUrl);
            return myVoice.getVoiceId();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public byte[] convertTextToSpeech(Integer audioToneId, String cloneVoiceId, String voice,
                                      String voice_path, String voice_hash,
                                      String voice_suffix, String response_format, String input) {
        log.info("文本转语音开始, cloneVoiceId = {}, input = {}", cloneVoiceId, input);
        long startTime = System.currentTimeMillis();

        try {
            final SpeechSynthesisParam param = SpeechSynthesisParam.builder()
                    .apiKey(aliConfig.getApiKey())
                    .model(targetModel)
                    .voice(cloneVoiceId)
                    .build();
            final SpeechSynthesizer synthesizer = new SpeechSynthesizer(param, null);
            final ByteBuffer audio = synthesizer.call(input);
            final byte[] audioData = audio.array();
            final long duration = System.currentTimeMillis() - startTime;
            log.info("文本转语音完成, cloneVoiceId = {}, audioData.len = {}, input = {}, duration = {}",
                    cloneVoiceId, audioData.length, input, duration);
            return audioData;
        } catch (Exception e) {
            final long duration = System.currentTimeMillis() - startTime;
            log.error(StrUtil.format("文本转语音异常, cloneVoiceId = {}, input = {}, duration = {}",
                    cloneVoiceId, input, duration), e);
            throw new RuntimeException("文本转语音请求异常", e);
        }
    }

}
